﻿using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using SignalRApp.Common;
using SignalRApp.Models;
using SignalRApp.Models.Dto;
using SignalRApp.Service;
using SignalRApp.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SignalRApp.SignalR
{
    /// <summary>
    /// 1:页面 模仿微信群 要求用flex 布局  头像/用户名/消息  url 里groupid 作为分组id
    /// 2：暂时只支持文本消息
    /// 
    /// </summary>
    [HubName("chat")]
    public class ChatHub:Hub
    {

        private readonly IChatRecordService _chatRecordService;
        private readonly IChatGroupService _chatGroupService;
        private readonly IUserService _userService;

        public ChatHub(IChatRecordService chatRecordService,
            IChatGroupService chatGroupService,
            IUserService userService)
        {
            _chatRecordService = chatRecordService;
            _chatGroupService = chatGroupService;
            _userService = userService;
        }

        public ChatHub()
        {
        }

        public int shit()
        {
            return 123;
        }

        /// <summary>
        /// 加入房间，初步设想在这里拉取聊天数据，如果不行可能需要重写onconection方法，试试看
        /// </summary>
        /// <param name="groupId"></param>
        public ChatHubResult Group(string groupId)
        {
            if (string.IsNullOrWhiteSpace(groupId))
            {
                //不用“群组Id”提示是突然想到给chatRecord加个tpye区分touser和togroup
                //就可以去掉touser字段，即将所有对话【群聊】、【私聊】都视为群组聊天
                return new ChatHubResult("空的对话Id");
            }
            Groups.Add(Context.ConnectionId, groupId);
            int.TryParse(groupId,out int id);
            
               
      
            var result= this.GetChatRecords(id);
            //todo
            //这里规定了群组名为空就视为不存在，所以添加群组那部分一定不能加个空群组名
            if (string.IsNullOrEmpty(result.GroupName))
            {
                return new ChatHubResult("不存在的对话");
            }
            return new ChatHubResult()
            {
                 Data=result
            };
        }
        //public void LeaveRoom(string user)
        //{
        //    return Groups.Remove(Context.ConnectionId, roomName);
        //}


        private ChatListViewModel GetChatRecords(int groupId)
        {
            string groupName = string.Empty;
            var group = _chatGroupService.GetById(groupId);
            groupName = group?.Name;
            var chatRecord = _chatRecordService.GetListByGroupId(groupId);
            var chatRecordDtos = (from s in chatRecord
                                  select new ChatRecordDto
                                  {
                                      Id = s.Id,
                                      Content = s.Content,
                                      CreateTime = s.CreateTime,
                                      From = s.From,
                                      ToGroup = s.ToGroup,
                                      ToUser = s.ToUser
                                  }).ToList();
            ChatListViewModel result = new ChatListViewModel
            {
                GroupName = groupName,
                Data = chatRecordDtos
            };

            return result;
        }

        /// <summary>
        /// 参数自己写
        /// </summary>
        public ChatHubResult SendMsg(InsertChatRecordDto msg)
        {
            if (msg==null)
            {
                return new ChatHubResult("不能发送空消息");
            }
            var saveMsgResult=this.saveMsg(msg);
            if (saveMsgResult.IsSuccess)
            {
                GlobalHost.ConnectionManager.GetHubContext<ChatHub>().Clients.All.receive("");
                //save to DB
                //发送给客户端
                Clients.Group((msg.ToGroupId).ToString()).receiveMsg(new {  msg, isSucess = saveMsgResult.IsSuccess });
                return new ChatHubResult();
            }
            else
            {

                //todo
                //初步设计： 返回给当前用户错误原因，比如被管理禁言不能发言
                return new ChatHubResult("不能发言");
            }
           
        }
        

        private SendMsgResultDto saveMsg(InsertChatRecordDto chatDto)
        {
            if (chatDto == null)
            {
                return new SendMsgResultDto {
                     IsSuccess=false,
                     Message="空消息"
                };
            }
            chatDto.CreateTime = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");
            var ToUser = _userService.GetUserById(chatDto.ToUserId);
            var FromUser = _userService.GetUserById(chatDto.FromUserId);
            var ToGroup = _chatGroupService.GetById(chatDto.ToGroupId);
            if (FromUser == null)
            {
                return new SendMsgResultDto("未知身份登录");
            }
            ChatRecord record = new ChatRecord
            {
                Content = chatDto.Content,
                 Type=chatDto.Type,
                CreateTime = chatDto.CreateTime,
                From = FromUser,
                Id = chatDto.Id,
                ToGroup = ToGroup,
                ToUser = ToUser
            };
            var result = _chatRecordService.InsertRecord(record);
            if (result > 0)
            {
               
                return new SendMsgResultDto();
            }
            return new SendMsgResultDto("服务器内部错误");
        }
    }
}
